<?php



// 执行HTTP应用并响应
class InstallModel {
    public function systemList() {
        return [
            'php' => [
                'name' => 'PHP',
                'version' => PHP_VERSION,
                'default' => '>=8.3.0',
                'status' => version_compare(PHP_VERSION, '8.3.0', '>=') ? '<div class="text-green-500">ok</div>' : '<div class="text-red-500">error</div>',
            ],
            'fileinfo' => [
                'name' => 'fileinfo',
                'version' => '存在',
                'default' =>  extension_loaded('fileinfo') ? '<div class="text-green-500">存在</div>' : '<div class="text-red-500">不存在</div>',
                'status' => extension_loaded('fileinfo') ? '<div class="text-green-500">ok</div>' : '<div class="text-red-500">error</div>',
            ],
            'gd' => [
                'name' => 'gd',
                'version' => '存在',
                'default' =>  extension_loaded('gd') ? '<div class="text-green-500">存在</div>' : '<div class="text-red-500">不存在</div>',
                'status' => extension_loaded('gd') ? '<div class="text-green-500">ok</div>' : '<div class="text-red-500">error</div>',
            ],
            'shell_exec'    => [
                'name' => 'shell_exec',
                'version' => '存在',
                'default' =>  function_exists('shell_exec') ? '<div class="text-green-500">存在</div>' : '<div class="text-red-500">不存在</div>',
                'status' => function_exists('shell_exec') ? '<div class="text-green-500">ok</div>' : '<div class="text-red-500">error</div>',
            ],
            
        ];
    }

    /**
     * Notes: 获取安装目录
     * @author luzg(2020/8/26 16:15)
     * @return string
     */
    public function getInstallRoot()
    {
        return INSTALL_ROOT;
    }

    public function getAppRoot()
    {
        return realpath($this->getInstallRoot() . '/../../');
    }



    public function checkEnvironment() {
        $systemList = $this->systemList();
        $pass = true;
        foreach ($systemList as $item) {
            if (strpos($item['status'], 'error') !== false) {
                $pass = false;
                break;
            }
        }
        return $pass;
    }
    
    public function checkDirPermission() {
        $checkDirs = [
            'runtime',
            'public/uploads',
        ];
        
        $results = [];
        foreach ($checkDirs as $dir) {
            $results[$dir] = [
                'path' => $dir,
                'required' => '可写',
                'status' => file_exists($this->getAppRoot() . DIRECTORY_SEPARATOR . $dir) ?
                    '<div class="text-green-500">可写</div>' :
                    '<div class="text-red-500">不可写</div>',
                'type' =>   file_exists($this->getAppRoot() . DIRECTORY_SEPARATOR . $dir)
            ];
        }
        return $results;
    }
    
//    public function install($config) {
//        try {
//            // 1. 检查环境
//            if (!$this->checkEnvironment()) {
//                throw new Exception('环境检查未通过，请检查系统要求');
//            }
//
//            // 2. 检查目录权限
//            $dirCheck = $this->checkDirPermission();
//            foreach ($dirCheck as $dir) {
//                if (strpos($dir['status'], 'red-500') !== false) {
//                    throw new Exception('目录权限检查未通过，请设置相应目录为可写');
//                }
//            }
//
//            // 3. 写入数据库配置
//            $dbConfig = [
//                'host' => $config['db_host'],
//                'database' => $config['db_name'],
//                'username' => $config['db_user'],
//                'password' => $config['db_password'],
//                'port' => $config['db_port'] ?? 3306,
//                'db_prefix'=>$config['db_prefix'] ?? 'matrix_',
//            ];
//
//            $this->writeConfig($dbConfig);
//
//            return ['status' => true, 'message' => '安装成功'];
//        } catch (Exception $e) {
//            return ['status' => false, 'message' => $e->getMessage()];
//        }
//    }
    
//    private function writeConfig($config) {
//        $configContent = "<?php\nreturn " . var_export($config, true) . ";\n";
//        file_put_contents(ROOT_PATH . '/config/database.php', $configContent);
//    }

    public function testDatabase($config) {
        try {
            // 先测试连接
            $dsn = "mysql:host={$config['db_host']};port={$config['db_port']}";
            $pdo = new PDO($dsn, $config['db_user'], $config['db_password']);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // 检查数据库是否存在
            $stmt = $pdo->query("SHOW DATABASES LIKE '{$config['db_name']}'");
            $dbExists = $stmt->rowCount() > 0;
            
            if (!$dbExists) {
                return [
                    'status' => false,
                    'message' => "数据库 {$config['db_name']} 不存在"
                ];
            }
            
            // 尝试切换到指定数据库
            $pdo->exec("USE `{$config['db_name']}`");
            
            // 检查权限
            $stmt = $pdo->query("SHOW GRANTS");
            $hasPermission = false;
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $grant = array_values($row)[0];
                if (strpos($grant, 'ALL PRIVILEGES') !== false || 
                    (strpos($grant, 'CREATE') !== false && strpos($grant, 'ALTER') !== false)) {
                    $hasPermission = true;
                    break;
                }
            }
            
            if (!$hasPermission) {
                return [
                    'status' => false,
                    'message' => '数据库用户权限不足，需要 CREATE 和 ALTER 权限'
                ];
            }
            
            return [
                'status' => true,
                'message' => '数据库配置正确'
            ];
            
        } catch (PDOException $e) {
            return [
                'status' => false,
                'message' => '数据库连接失败：' . $e->getMessage()
            ];
        }
    }

    public function checkDatabaseEmpty($config) {
        $dsn = "mysql:host={$config['db_host']};port={$config['db_port']}";
        $pdo = new PDO($dsn, $config['db_user'], $config['db_password']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $pdo->query("SHOW DATABASES");
        $databases = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        return empty($databases) ? true : false;
    }

    public function clearDatabase($config) {
        $dsn = "mysql:host={$config['db_host']};port={$config['db_port']}";
        $pdo = new PDO($dsn, $config['db_user'], $config['db_password']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $pdo->query("SHOW DATABASES");
        $databases = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        foreach ($databases as $database) {
            $pdo->exec("DROP DATABASE IF EXISTS `{$database}`");
        }
        
        return true;    
    }

    public function executeInstallStep($step, $config = null) {
        // 模拟后台处理时间
        sleep(1);

        switch ($step) {
            case 'init':
                return [
                    'status' => true,
                    'step' => 'init',
                    'message' => '初始化安装环境...',
                    'detail' => '正在加载配置信息',
                    'progress' => 10
                ];

            case 'database':
                return [
                    'status' => true,
                    'step' => 'database',
                    'message' => '创建数据表...',
                    'detail' => [
                        'CREATE TABLE users...',
                        'CREATE TABLE settings...',
                        'CREATE TABLE posts...'
                    ],
                    'progress' => 30
                ];

            case 'import':
                return [
                    'status' => true,
                    'step' => 'import',
                    'message' => '导入基础数据...',
                    'detail' => [
                        'Importing system settings...',
                        'Importing default templates...',
                        'Importing demo data...'
                    ],
                    'progress' => 60
                ];

            case 'adminapi':
                return [
                    'status' => true,
                    'step' => 'adminapi',
                    'message' => '创建管理员账号...',
                    'detail' => [
                        'Creating adminapi user...',
                        'Setting up permissions...'
                    ],
                    'progress' => 80
                ];

            case 'finish':
                return [
                    'status' => true,
                    'step' => 'finish',
                    'message' => '完成安装...',
                    'detail' => '安装成功！',
                    'progress' => 100
                ];

            default:
                return [
                    'status' => false,
                    'message' => '未知的安装步骤'
                ];
        }
    }
}
